package com.loren.scheme;

import com.loren.config.DynamicDataSourceHolder;
import com.loren.constant.DataSourceContant;
import com.loren.entity.DbInfo;
import com.loren.entity.Person;
import com.loren.repository.DbInfoRepository;
import com.loren.repository.PersonRepository;
import com.loren.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DataScheme implements CommandLineRunner {

    @Value("${custom.default.datasource.db-url}")
    private String databaseUrl;

    @Value("${custom.default.datasource.db-user-name}")
    private String dbUserName;

    @Value("${custom.default.datasource.db-password}")
    private String dbPassword;

    @Autowired
    private DbInfoRepository dbInfoRepository;

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private PersonService personService;

    @Override
    public void run(String... args) {
//        切换到默认库
        DynamicDataSourceHolder.setDataSourceType(DataSourceContant.DEFAULT_DATASOURCE);
        if (!this.dbInfoRepository.findById(DataSourceContant.PERSON_DATASOURCE_ID).isPresent()) {
            DbInfo dbInfo = new DbInfo();
            dbInfo.setDataSourceId(DataSourceContant.PERSON_DATASOURCE_ID);
            dbInfo.setDbDriver("com.mysql.jdbc.Driver");
            dbInfo.setDbUrl(this.databaseUrl.replace("datasource_test_1", "datasource_test_2"));
            dbInfo.setDbUser(this.dbUserName);
            dbInfo.setDbPass(this.dbPassword);
            this.dbInfoRepository.save(dbInfo);
        }


//        切换到Person表所在的库
        DynamicDataSourceHolder.setDataSourceType(String.valueOf(DataSourceContant.PERSON_DATASOURCE_ID));

        if (!this.personRepository.findById(1).isPresent()) {
            Person person = new Person();
            person.setId(1);
            person.setName("第1个Person");
            this.personRepository.save(person);
        }

    }
}
